<template>
    <div class="components-container" v-cloak>
        <sweet-modal ref="dialog" class="dialog" :sweetModalMaxWidth="pageWidth">
            <h3>{{title}}</h3>
            <div style="margin:10px 20px">
                <div class="layui-form-item">
                    <div class="layui-inline" v-if="showno">
                        <label class="layui-form-label">调库单号</label>
                        <div class="layui-input-inline">
                           <el-input v-model="regInfo.DPOFORMTYPEID" readonly></el-input>
                        </div>
                    </div>
                    <div class="layui-inline">
                        <label class="layui-form-label">调库日期</label>
                        <div class="layui-input-inline backcolor">
                            <el-date-picker v-date type="date" v-model="DPOGRANTDATE" :readonly="!iscomeinfo"></el-date-picker>
                        </div>
                    </div>
                     <div class="layui-inline">
                        <label class="layui-form-label">总金额</label>
                        <div class="layui-input-inline">
                            <el-input v-model="regInfo.DPOMONEY" :readonly="!iscomeinfo"></el-input>
                        </div>
                    </div>
                </div>
                <div class="layui-form-item">
                    <div class="layui-inline">
                        <label class="layui-form-label">申请人</label>
                        <div class="layui-input-inline">
                            <el-input v-model="regInfo.DPOAPPLYMAN" :readonly="!iscomeinfo"></el-input>
                        </div>
                    </div>
                    <div class="layui-inline">
                        <label class="layui-form-label">备注</label>
                        <div class="layui-input-inline">
                             <el-input type="textarea" v-model="regInfo.DPOREMARKS" :readonly="!iscomeinfo" style="width:495px;" placeholder="请输入备注" />
                        </div>
                    </div>
                </div>
            </div>
            <div :style="{maxHeight:maxHeight+'px'}" style="overflow:auto;">
                <table class="layui-table" style="border-spacing: 0;">
                    <thead>
                        <tr>
                            <th>所属仓库</th>
                            <th>物品名称</th>
                            <th>库存数量</th>
                            <th>调整数量</th>
                            <th v-if="isshowmoney">金额</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody ref='inputs'>
                        <tr class="allRow" v-for="(chl,index) in chlList">
                            <td>
                                <!-- @keydown.enter.native="enterEvent(index,0)" -->
                                <el-select @change="chaSelect($event,index)" ref="select" v-model="chl.DOLDEPOSIT" clearable :disabled='isINFO' filterable>
                                    <el-option v-for="item in StoragePosition" :key="item.CodeValue" :label="item.CodeName" :value="item.CodeValue">
                                    </el-option>
                                </el-select>
                            </td>
                            <td>
                                <el-select @change="kucunnum(chl,index)" @visible-change="xialakuang(chl,$event)" ref="selects" v-model="chl.DOLDPGID" clearable :filter-method="chaFilter" :disabled='isINFO' filterable>
                                    <el-option id="goodname" v-for="item in istrue? returnDepot(chl) : alldatas" :key="item.SOKDPGID" :label="item.DPGNAME" :value="item.SOKDPGID">
                                    </el-option>
                                </el-select>
                            </td>
                            <td>
                                <!-- @keydown.enter.native="enterEvent(index,1)" -->
                                <!-- SOKUSABLENUM -->
                                <el-input v-model="chl.DOLIDESOK" disabled>
                                </el-input>
                            </td>
                            <td>
                                <el-input @keyup.native="check(index)"  @input="CalculationMoney(chl,$event)" v-model="chl.DOLNUM" :disabled='isINFO'>
                                </el-input>
                            </td>
                            <td v-if="isshowmoney">
                                <el-input v-model="chl.DOLMONEY" :disabled='isINFO'>
                                </el-input>
                            </td>
                            <td>
                                <button class="layui-btn layui-btn-small layui-btn-normal" @click="remove(index)" :disabled='isINFO'>
                                    <i class="layui-icon">&#xe640;</i>
                                </button>
                            </td>
                        </tr>
                    </tbody>
                    <tfoot>
                        <tr>
                            <td v-if="isshowmoney" colspan="5"></td>
                            <td v-if="!isshowmoney" colspan="4"></td>
                            <td>
                                <button class="layui-btn layui-btn-small layui-btn-normal" @click="insert()" :disabled='isINFO'>
                                    <i class="layui-icon">&#xe654;</i>
                                </button>
                            </td>
                        </tr>
                    </tfoot>
                </table>
            </div>
            <div class="layui-form-item btnCenter sweet-btn">
                <el-button @click="closeDialog">取消</el-button>
                <el-button type="primary" @click="submit()" :loading="this.$store.state.isloading" v-if="!(this.title === '商品调库单详情')">提交</el-button>
            </div>
        </sweet-modal>
    </div>
</template>
<style rel="stylesheet/scss" lang="scss" scoped>
@import "src/styles/common.scss";
.el-button + .el-button {
    margin-left: 0;
}

.sweet-btn {
    margin-top: 20px;
}
</style>

<script>
import sweetModal from "@/components/sweetModal";
import apiBase from "@/api/apiBase.js";
import { formatDate, timeStringToDate } from "@/utils/date.js";
import { accMul, Subtr, accAdd } from "@/utils/operations.js";
import { ORDER } from "@/const/orderConst.js";

const APPLY = "新增";
const MODIFY = "修改";
const DELETE = "删除";
const PRINTING = "打印";
const INFO = "详情";


export default {
    name: "hello",
    data() {
        return {
            showno:false,
            isINFO: false,
            pageWidth: 1200,
            maxHeight: 500,
            CHDID: null,
            order: null,
            title: null,
            reginfoid: null,//regid
            //所有收费项目
            allCharge: [],
            chaList: [],
            //收费信息
            chdData: {},
            regInfo: {
                DPOFORMTYPEID: null,//调库单号
                DPOMONEY: null,//总金额
                DPOAPPLYMAN: null,//使用人
                DPOREMARKS: null,//备注
            },
            DPOGRANTDATE: null,//调库日期
            crhData: {
            },
            //收费项目
            chlList: [],
            //物品名称
            Depot: [],
            //所属仓库
            StoragePosition: [],
            chl: {
                DOLDEPOSIT: null, //所属仓库
                DOLDPGID: "", //物品类别编号
                DOLIDESOK: null, //库存数量
                DOLNUM: null, //出库数量
                DOLMONEY: null //出库金额
            },
            DPOID: null,
            isINFO: false,
            isshowmoney: null,
            iscomeinfo: null,
            allstock: [],
            istrue: true,
            alldatas: [],
            chls: {},
        };
    },
    methods: {
        //新增行
        insert() {
            for (let index in this.chlList) {
                let chl = this.chlList[index];
                if(this.isshowmoney){
                    if (
                        chl.DOLDEPOSIT === null ||
                        chl.DOLDPGID === null ||
                        chl.DOLNUM === null ||
                        chl.DOLMONEY === null
                    ) {
                        this.$message({
                            type: "error",
                            message: `第${parseInt(index) + 1}行信息不能有空!`
                        });
                        return false;
                    }
                }else{
                    if (
                        chl.DOLDEPOSIT === null ||
                        chl.DOLDPGID === null ||
                        chl.DOLNUM === null
                    ) {
                        this.$message({
                            type: "error",
                            message: `第${parseInt(index) + 1}行信息不能有空!`
                        });
                        return false;
                    }
                }
            }
            this.chlList.push(JSON.parse(JSON.stringify(this.chl)));
            return true;
        },
        //删除行
        remove(index) {
            this.chlList.splice(index, 1);
        },
        //回车事件
        // enterEvent(rowNum, colNum) {
        //   //获取所有行
        //   let rows = this.$refs.inputs.getElementsByClassName("allRow");
        //   //获取当前行
        //   let currow = rows[rowNum];
        //   // 获取当前行所有列
        //   let inputs = currow.getElementsByTagName("input");
        //   //强制隐藏下拉框
        //   if (colNum === 0) {
        //     let chl = this.chlList[rowNum];
        //     if (chl.CHLCHAID.length === 0) {
        //       this.$message({
        //         type: "error",
        //         message: `第${parseInt(rowNum) + 1}行收费项目不能为空!`
        //       });
        //       return;
        //     }
        //     let select = this.$refs.select;
        //     select[rowNum].visible = false;
        //   }
        //   //最后一列
        //   if (colNum === inputs.length - 1) {
        //     //最后一行
        //     if (rowNum === this.chlList.length - 1) {
        //       //插入空行
        //       if (!this.insert()) {
        //         return;
        //       }
        //     }
        //     //换行
        //     this.$nextTick(function () {
        //       this.enterEvent(rowNum + 1, -1);
        //     });
        //   } else {
        //     //获取下一个焦点
        //     this.$nextTick(function () {
        //       inputs[colNum + 1].select();
        //     });
        //   }
        // },
        //禁用已选项
        //   disabled(chaID) {
        //     let retVal = this.chlList.some(item => {
        //       return item.CHLCHAID === chaID;
        //     });
        //     return retVal;
        //   },
 
    
        datareapet(){
             Object.assign(this.$data.regInfo,this.$options.data().regInfo);
            
        },
        //打开弹出框
        open(order, id) {
            this.order = order;
            this.DPOID = id;
            this.iscomeinfo = true;
            this.istrue = true;
            this.getallstock();
            this.getstock();
            switch (this.order) {
                case APPLY:
                    this.title = "商品调库单新增";
                    this.chl.DOLDEPOSIT = this.StoragePosition[0].CodeValue;
                    this.isINFO = false;
                    this.showno = false;
                    this.chlList = [];
                    this.datareapet();
                    this.insert();
                    // this.getstock(); //获取库存
                    this.DPOGRANTDATE = new Date();
                    this.regInfo.DPOAPPLYMAN = localStorage.getItem("username");
                    this.$refs.dialog.open();
                    break;
                case MODIFY:
                    this.title = "商品调库单修改";
                    this.isINFO = false;
                    this.showno = true;
                    this.chlList = [];
                    this.datareapet();
                    this.dataInfo(id);
                    this.$refs.dialog.open();
                    break;
                case INFO:
                    this.title = "商品调库单详情";
                    this.isINFO = true;
                    this.showno = true;
                    this.iscomeinfo = false;
                    this.chlList = [];
                    this.datareapet();
                    this.dataInfo(id);
                    this.$refs.dialog.open();
                default:
            }
        },
        //出库详情
        dataInfo(id) {
            let data = {
                DPOID: id
            };
            apiBase.DoService(
                data,
                apiBase.getApiAdress().Depot.DetailDpo,
                res => {
                    this.chdData = res.data.content;
                    this.regInfo.DPOAPPLYMAN = this.chdData.DPOAPPLYMAN;   //使用人
                    this.regInfo.DPOREMARKS = this.chdData.DPOREMARKS;
                    this.regInfo.DPOFORMTYPEID  = this.chdData.DPOFORMTYPEID;
                    this.regInfo.DPOMONEY  = this.chdData.DPOMONEY;
                    this.DPOGRANTDATE = this.chdData.DPOVERIFYDPTDESC;
                    this.chlList = this.chdData.List_Dpl;
                    //用于修改页面
                    if (this.iscomeinfo) {
                        for (var s = 0; s < this.chlList.length; s++) {
                            for (var i = 0; i < this.Depot.length; i++) {
                                if (
                                    this.Depot[i].SOKDPGID === this.chlList[s].DOLDPGID
                                ) {
                                    this.chlList[s].DOLIDESOK = this.Depot[i].SOKUSABLENUM;
                                }
                            }
                        }
                    } else {
                        //用于详情页面
                        for (var s = 0; s < this.chlList.length; s++) {
                            this.chlList[s].DOLIDESOK = this.chlList[s].DOLIDESOK;
                        }
                    }
                }
            );
        },

        xialakuang(chl,booler){
            this.chls = chl;
            if(booler === false) return;
            this.istrue = true;
        },
        //动态获取库存
        returnDepot(val){
            for(var i = 0;i < this.allstock.length;i++){
                if(this.allstock[i].length != 0 && this.allstock[i][0].SOKDEPOSIT === val.DOLDEPOSIT){  
                    this.allCharge = this.allstock[i]; 
                    return this.allstock[i];
                }
            }
        },  
        //获取库存
        getstock() {
            let data = {
                SOKDEPOSIT: this.StoragePosition[0].CodeValue
            };
            apiBase.DoService(
                data,
                apiBase.getApiAdress().Depot.QueryAllDpgs,
                res => {
                    this.allCharge = res.data.content;
                    this.Depot = res.data.content;
                }
            );
        },
        // 获取所有的库存
        getallstock(){
            this.allstock = [];
            for(var i = 0;i < this.StoragePosition.length;i++){
                let data = {
                    SOKDEPOSIT: this.StoragePosition[i].CodeValue
                };
                apiBase.DoService(
                    data,
                    apiBase.getApiAdress().Depot.QueryAllDpgs,
                    res => {
                        this.allstock.push(res.data.content);
                    }
                );
            }
        },

        //获取仓库存放位置
        getwarehouseadress() {
            let data = {};
            apiBase.DoService(
                data,
                apiBase.getApiAdress().Code.GetDepot,
                res => {
                    this.StoragePosition = res.data.content;
                }
            );
        },
        //
        chaSelect(index, num) {
            let data = {
                SOKDEPOSIT: index
            };
            apiBase.DoService(
                data,
                apiBase.getApiAdress().Depot.QueryAllDpgs,
                res => {
                    this.allCharge = res.data.content;
                    this.Depot = res.data.content;
                }
            );
            this.chlList[num].DOLDPGID = null;
            this.chlList[num].DOLNUM = null;  
            this.chlList[num].DOLMONEY = null;
        },
        kucunnum(val, num) {
            if (this.iscomeinfo === false) return false;
            var datas = [];
            for(var i = 0;i < this.allstock.length;i++){
                if(this.allstock[i].length != 0 && this.allstock[i][0].SOKDEPOSIT === val.DOLDEPOSIT){  
                    datas = this.allstock[i];
                }
            };
            for (var i = 0; i < datas.length; i++) {
                if (datas[i].SOKDPGID === val.DOLDPGID) {
                    this.chlList[num].DOLIDESOK = datas[i].SOKUSABLENUM;
                    this.chlList[num].DOLNUM = null;  
                    this.chlList[num].DOLMONEY = null;
                }
            }
        },
        reset() {
            this.chaList = JSON.parse(JSON.stringify(this.allCharge));
        },
        //获取常用项
        //   getCommonItem() {
        //     let data = {
        //       Data: {
        //         "REGYITIQX": this.regInfo.REGYITIQX,
        //         "REGGHQX": this.regInfo.REGGHQX
        //       }
        //     };
        //     apiBase.DoService(data, apiBase.getApiAdress().CommonItem.Query, res => {
        //       let common = res.data.content.OutData;
        //       common.forEach(item => {
        //         var isContain = this.chlList.some(chl => {
        //           return item.CNOCHAID === chl.CHLCHAID;
        //         });
        //         if (!isContain) {
        //           let chl = JSON.parse(JSON.stringify(this.chl));
        //           let cha = this.getChaByID(item.CNOCHAID);
        //           if (cha) {
        //             chl.CHLCHAID = cha.CHAID;
        //             chl.CHLCHANAME = cha.CHANAME;
        //             chl.CHLAUNIT = cha.CHAAUNIT;
        //             chl.CHLMONEY = cha.CHAMONEY;
        //             chl.CHLNUM = 1;
        //             chl.CHLMOUNT = chl.CHLMONEY * chl.CHLNUM;
        //             chl.CHLREDUCTION = cha.CHAJMMONEY * chl.CHLNUM;
        //             chl.CHLDISCOUNT = cha.CHADISCOUNT * chl.CHLNUM;
        //             chl.CHLRECEIVED =
        //               chl.CHLMOUNT - chl.CHLREDUCTION - chl.CHLDISCOUNT;
        //           }
        //           this.chlList.push(chl);
        //         }
        //       });
        //       this.chlList = this.chlList.filter(item => {
        //         return item.CHLCHAID && item.CHLCHAID.length > 0;
        //       });
        //       this.chlList.push(JSON.parse(JSON.stringify(this.chl)));
        //     });
        //   },
        //ID获取收费项目
        getChaByID(chaId) {
            for (var i in this.allCharge) {
                var cha = this.allCharge[i];
                if (cha.CHAID === chaId) {
                    return cha;
                }
            }
        },
        check(index) {
            let chl = this.chlList[index];
            let bookname;
            if(this.Depot){
                for(var i = 0;i < this.Depot.length;i++){
                    if(this.Depot[i].SOKDPGID == chl.DOLDPGID){
                        bookname = this.Depot[i].DPGNAME;
                    }
                }
            }
            // chl.CHLMONEY = this.checkMoney(chl.CHLMONEY.toString());
            chl.DOLNUM = this.checkNumber(chl.DOLNUM.toString());
            if(chl.DOLNUM > chl.DOLIDESOK){
                this.$message({
                    message: '物品[' + bookname +  ']' +  '库存不足！',
                    type: 'warning'
                });
            }
            // chl.CHLDISCOUNT = this.checkMoney(chl.CHLDISCOUNT.toString());
        },
        isCommon() {
            return this.order === ORDER.CHEMODIFY;
        },
        // //只能输入正整数
        // checkNumber(value) {
        //     value = value.replace(/\D/g, "").replace(/^0+(?=\d)/, "");
        //     if (value !== "") {
        //         if (value.substr(0, 1) === "0" && value.length === 2) {
        //             value = value.substr(1, value.length);
        //         }
        //     } else {
        //         value = 0;
        //     }
        //     return value;
        // },
        //只能输入整数 （正 负都可以）
        checkNumber(value) {
            if(value.length==1){value=value.replace(/[^(\-?)\d+]/ig,'')}
            else{value=value.substring(0,1)+value.substring(1,value.length).replace(/[^\d+]/ig,'');}
            return value;
        },
        //只能输入金额
        checkMoney(value) {
            //修复第一个字符是小数点 的情况.
            if (value !== "" && value.substr(0, 1) === ".") {
                value = "";
            }
            value = value.replace(/^0*(0\.|[1-9])/, "$1"); //解决 粘贴不生效
            value = value.replace(/[^\d.]/g, ""); //清除“数字”和“.”以外的字符
            value = value.replace(/\.{2,}/g, "."); //只保留第一个. 清除多余的
            value = value
                .replace(".", "$#$")
                .replace(/\./g, "")
                .replace("$#$", ".");
            value = value.replace(/^(\-)*(\d+)\.(\d\d).*$/, "$1$2.$3"); //只能输入两个小数
            if (value.indexOf(".") < 0 && value !== "") {
                //以上已经过滤，此处控制的是如果没有小数点，首位不能为类似于 01、02的金额
                if (value.substr(0, 1) === "0" && value.length === 2) {
                    value = value.substr(1, value.length);
                }
            } else if (value === "") {
                value = 0;
            }
            return value;
        },
        //计算当前行CHL
        chlCompute(index) {
            let chl = this.chlList[index];
            let cha = this.getChaByID(chl.CHLCHAID);
            if (cha) {
                chl.CHLMOUNT = chl.CHLMONEY * chl.CHLNUM;
                chl.CHLREDUCTION = cha.CHAJMMONEY * chl.CHLNUM;
                chl.CHLRECEIVED =
                    chl.CHLMOUNT - chl.CHLREDUCTION - chl.CHLDISCOUNT;
            }
        },
        //自定义筛选
        chaFilter(val) {
            var copydata = [];
            var datas = [];
            for(var i = 0;i < this.allstock.length;i++){
                if(this.allstock[i].length != 0 && this.allstock[i][0].SOKDEPOSIT === this.chls.DOLDEPOSIT){  
                    datas = this.allstock[i];
                }
            };
            this.istrue = false;
            if (val) {
                if (val.length > 0){
                    copydata = datas.filter(item => {
                        return (
                            item.DPGNAME.indexOf(val) > -1 ||
                            item.DPGCODE.toLowerCase().indexOf(
                                val.toLowerCase()
                            ) > -1
                        );
                    });
                    this.alldatas = copydata;
                }    
            }else{
                this.alldatas = datas;
            } 
        },
        // 计算金额
        CalculationMoney(val, num) {
            var datas = [];
            for(var i = 0;i < this.allstock.length;i++){
                if(this.allstock[i].length != 0 && this.allstock[i][0].SOKDEPOSIT === val.DOLDEPOSIT){  
                    datas = this.allstock[i];
                }
            };
            if (this.isshowmoney) {
                for (var i = 0; i < datas.length; i++) {
                    if (datas[i].SOKDPGID === val.DOLDPGID) {
                        val.DOLMONEY = datas[i].DPGSALE * Number(num);
                    }
                }
            }
        },
        //提交
        submit(checkout = false) {
            this.$store.state.isloading = true;
            switch (this.order) {
                case APPLY: //新增
                    this.dataAdd(checkout);
                    break;
                case MODIFY:
                    this.changesrk();
                default:
                    break;
            }
        },
        //新增
        dataAdd() {
            let chlList = JSON.parse(JSON.stringify(this.chlList));
            let data = JSON.parse(JSON.stringify(this.regInfo));
            data.DPOREGID = this.reginfoid;
            if(this.DPOGRANTDATE){
                data.DPOGRANTDATE =  formatDate(this.DPOGRANTDATE, "yyyyMMdd");
            }
            // data.DOLIDESOK =
            if (chlList.length > 0) {
                data.list_Dol = chlList;
            }
            apiBase.DoService(
                data,
                apiBase.getApiAdress().Depot.FuneralThingsAdjustLibrary,
                res => {
                    this.$message({
                        type: "success",
                        message: "调库成功!"
                    });
                    this.DPOID = res.data.content.DPOID;
                    this.closeDialog();
                    this.refreshData();
                }
            );
        },

        //修改
        changesrk() {
            let chlList = JSON.parse(JSON.stringify(this.chlList));
            let data = JSON.parse(JSON.stringify(this.regInfo));
            if(this.DPOGRANTDATE){
                data.DPOGRANTDATE =  formatDate(this.DPOGRANTDATE, "yyyyMMdd");
            }
            if (chlList.length > 0) {
                data.list_Dol = chlList;
            }
            (data.DPOID = this.DPOID),
                apiBase.DoService(
                    data,
                    apiBase.getApiAdress().Depot.ModifyFuneralThingsAdjustLibrary,
                    res => {
                        this.$message({
                            type: "success",
                            message: "修改成功!"
                        });
                        this.closeDialog();
                        this.refreshData();
                    }
                );
        },
        closeDialog() {
            switch (this.order) {
                case APPLY:
                case MODIFY:
                case INFO:
                    this.$refs.dialog.close();
                    break;
                default:
                    break;
            }
        },
        refreshData() {
            this.$emit("refreshData");
        },
    },
    created() {
        this.getwarehouseadress(); //获取仓库
        let data = {};
        apiBase.DoService(
            data,
            apiBase.getApiAdress().Param.GetDepotisPrice,
            res => {
                this.isshowmoney = res.data.content;
            }
        );
    },
    //计算属性
    computed: {
        mountTotal() {
            let total = 0;
            for (let chl of this.chlList) {
                total = accAdd(total, chl.CHLMOUNT);
            }
            return total;
        },
        reductionTotal() {
            let total = 0;
            for (let chl of this.chlList) {
                total = accAdd(total, chl.CHLREDUCTION);
            }
            return total;
        },
        discountTotal() {
            let total = 0;
            for (let chl of this.chlList) {
                total = accAdd(total, chl.CHLDISCOUNT);
            }
            return total;
        },
        chlreceivedTotal() {
            let total = 0;
            for (let chl of this.chlList) {
                total = accAdd(total, chl.CHLRECEIVED);
            }
            return total;
        },
        isAdd() {
            return this.order === ORDER.ADD || this.order === ORDER.RETMODIFY;
        }
    },

    watch: {
       
    },
    mounted() {
        apiBase.DoService(
            {},
            apiBase.getApiAdress().Param.GetBackgroundColor,
            res => {
                let backcolor = "";
                if (res.data.content === "20") {
                    const inputs = document.querySelectorAll(
                        ".backcolor input.el-input__inner"
                    );
                    backcolor = "rgb(255,255,153)";
                    for (var i = 0; i < inputs.length; i++) {
                        inputs[i].style.backgroundColor = backcolor;
                    }
                }
            }
        );
    },
    components: {
        sweetModal
    }
};
</script>
